const getCustomEvent = function() {
    if (typeof window.CustomEvent === "function") return false

    const CustomEvent = function(event, params) {
        params = params || { bubbles: false, cancelable: false, detail: undefined }
        var evt = document.createEvent('CustomEvent')
        evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail)
        return evt
    }
    CustomEvent.prototype = window.Event.prototype
    window.CustomEvent = CustomEvent
}

const getNewXHR = function() {
    const ajaxEventTrigger = function(event) {
        var ajaxEvent = new CustomEvent(event, { detail: this })
        window.dispatchEvent(ajaxEvent)
    }

    const oldXHR = window.XMLHttpRequest

    const newXHR = function() {
        const realXHR = new oldXHR()
        realXHR.addEventListener('abort', function() { ajaxEventTrigger.call(this, 'ajaxAbort') }, false)
        realXHR.addEventListener('error', function() { ajaxEventTrigger.call(this, 'ajaxError') }, false)
        realXHR.addEventListener('load', function() { ajaxEventTrigger.call(this, 'ajaxLoad') }, false)
        realXHR.addEventListener('loadstart', function() { ajaxEventTrigger.call(this, 'ajaxLoadStart') }, false)
        realXHR.addEventListener('progress', function() { ajaxEventTrigger.call(this, 'ajaxProgress') }, false)
        realXHR.addEventListener('timeout', function() { ajaxEventTrigger.call(this, 'ajaxTimeout') }, false)
        realXHR.addEventListener('loadend', function() { ajaxEventTrigger.call(this, 'ajaxLoadEnd') }, false)
        realXHR.addEventListener('readystatechange', function() { ajaxEventTrigger.call(this, 'ajaxReadyStateChange') }, false)

        let send = realXHR.send
        realXHR.send = function(...arg) {
            send.apply(realXHR, arg)
            realXHR.body = arg[0]
            ajaxEventTrigger.call(realXHR, 'ajaxSend')
        }

        let open = realXHR.open
        realXHR.open = function(...arg) {
            open.apply(realXHR, arg)
            realXHR.method = arg[0]
            realXHR.orignUrl = arg[1]
            realXHR.async = arg[2]
            ajaxEventTrigger.call(realXHR, 'ajaxOpen')
        }

        let setRequestHeader = realXHR.setRequestHeader
        realXHR.requestHeader = {}
        realXHR.setRequestHeader = function(name, value) {
            realXHR.requestHeader[name] = value
            setRequestHeader.call(realXHR, name, value)
        }
        return realXHR
    }
    window.XMLHttpRequest = newXHR
}

const listenAjaxSend = function() {
    let networkIndex = 1
    window.addEventListener("ajaxReadyStateChange", function(e) {
        let xhr = e.detail
        if (xhr.readyState == 4) {
            // xhr.getAllResponseHeaders()  响应头信息
            // xhr.requestHeader            请求头信息
            // xhr.responseURL              请求的地址
            // xhr.responseText             响应内容
            // xhr.orignUrl                 请求的原始参数地址
            // xhr.body                     post参数，（get参数在url上面）
            // log(304, xhr)
            const url = new URL(xhr.orignUrl)
            const statusMap = {
                200: '200 OK',
                301: '301 Move',
                302: '302 Found',
                404: '404 Not Found',
                500: '500 Error',
            }
            const methodMap = {
                get: 'GET',
                post: 'POST',
            }
            const networkObj = {
                name: url.pathname,
                status: statusMap[xhr.status] || 'Error',
                type: methodMap[xhr.method],
            }
            const networkDetail = {
                url: xhr.orignUrl,
                contentType: xhr.requestHeader?.['Content-Type'],
                method: methodMap[xhr.method],
                status: statusMap[xhr.status] || 'Error',
                userAgent: navigator.userAgent,
            }
            let networkTemplate = `
            <div class="table-info" id="${networkIndex}">
                <div class="table-network-row">
                    <div class="item-network-output network-name">${networkObj.name}</div>
                    <div class="item-network-output network-status">${networkObj.status}</div>
                    <div class="item-network-output network-type">${networkObj.type}</div>
                    <div class="item-network-output network-other"></div>
                </div>
                <div class=" table-detail none-show">
                    <div class="detail-item">
                        <strong>General</strong>
                    </div>
                    <div class="detail-item">
                        <strong>Request URL : </strong>
                        <span class="detail-item-content">${networkDetail.url}</span>
                    </div>
                    <div class="detail-item">
                        <strong>Content-Type : </strong>
                        <span class="detail-item-content">${networkDetail.contentType}</span>
                    </div>
                    <div class="detail-item">
                        <strong>Request Method : </strong>
                        <span class="detail-item-content">${networkDetail.method}</span>
                    </div>
                    <div class="detail-item">
                        <strong>Status Code : </strong>
                        <span class="detail-item-content">${networkDetail.status}</span>
                    </div>
                    <div class="detail-item">
                        <strong>User-Agent : </strong>
                        <span class="detail-item-content">${networkDetail.userAgent}</span>
                    </div>
                </div>
        </div>
        `
            const e = sel => document.querySelector(sel)
            let network = e('#console-network')
            network.innerHTML += networkTemplate
            networkIndex += 1
            // console.log(95, xhr.orignUrl)
            // log(94, url)
            // log(94, url.origin)
            // log(94, url.pathname)
            // console.log(95, xhr.requestHeader?.['Content-Type'])
            // console.log(95, xhr.method)
            // console.log(95, xhr.status)
            // console.log(95, navigator.userAgent)

            // console.log(96, xhr)
        }
    })
}

const __setAjaxInit = function() {
    getCustomEvent()
    getNewXHR()

    listenAjaxSend()
}

__setAjaxInit()
